package com.lvtongka.app.ui.qr

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.androideasy.permissions.EasyPermissions
import com.androideasy.permissions.Permission
import com.google.zxing.client.android.MNScanManager
import com.google.zxing.client.android.model.MNScanConfig
import com.zw.pass.dialog.PayPassDialog
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.base.BaseApplication
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.common.CommonUtils
import com.lvtongka.app.common.ZXingUtils
import com.lvtongka.app.databinding.FragmentPaymentCodeBinding
import com.lvtongka.app.dialog.CouponSelectDialog
import com.lvtongka.app.dialog.DialogRealName
import com.lvtongka.app.dialog.FuncScanDialog
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.fragment.common.SetPayCallback
import com.lvtongka.app.fragment.home.bean.TravelPassAssets
import com.lvtongka.app.fragment.home.bean.TravelPassAssetsData
import com.lvtongka.app.helper.SPHelper
import com.lvtongka.app.helper.SPKConstants
import com.lvtongka.app.okpermission.PermissionLauncher
import com.lvtongka.app.ui.coupon.bean.CouponItem
import java.util.Timer
import java.util.TimerTask

class PaymentCodeActivity : BaseActivity<FragmentPaymentCodeBinding, PaymentCodeViewModel>() {
    private var assetsData : TravelPassAssetsData? = null
    private var passAssetsData: TravelPassAssets? = null
    private var couponSelectDialog: CouponSelectDialog? = null
    private var dialogRealName: DialogRealName? = null
    private var payPassDialog: PayPassDialog? = null
    private val mBeanList: MutableList<CouponItem> = mutableListOf()
    private var resultSuccess: String? = null

    private var dynCode: String = ""
    private var isFinish = false
    private var isPause = false
    private var selectPosition = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        isBlack = false
        super.onCreate(savedInstanceState)
    }

    override fun initViewModel(): PaymentCodeViewModel {
        return ViewModelProvider(this)[PaymentCodeViewModel::class.java]
    }

    @SuppressLint("SetTextI18n")
    override fun initEvent() {
        binding.imgBack.setOnClickListener {
            isFinish = true
            finish()
        }
        binding.rlSys.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val isRealName = SPHelper.getBoolean(SPKConstants.IS_REAL_NAME)
            if (!isRealName) {
                DialogHelper.showRealNameHintDialog(this) {
                    showRealNameDialog()
                }
                return@setOnClickListener
            } else {
                val isSetPwd = SPHelper.getBoolean(SPKConstants.IS_SET_PWD)
                if (!isSetPwd) {
                    // 未设置支付密码
                    showSetPay()
                    return@setOnClickListener
                }
                val isFuncScan = SPHelper.getBoolean(SPKConstants.IS_FUNC_SCAN)
                if (!isFuncScan) {
                    DialogHelper.showScanPayDialog(this){
                        showFuncScanDialog()
                    }
                    return@setOnClickListener
                }
                scan()
            }
        }
        binding.tvOpen.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val isRealName = SPHelper.getBoolean(SPKConstants.IS_REAL_NAME)
            if (!isRealName) {
                DialogHelper.showRealNameHintDialog(this) {
                    showRealNameDialog()
                }
                return@setOnClickListener
            } else {
                val isSetPwd = SPHelper.getBoolean(SPKConstants.IS_SET_PWD)
                if (!isSetPwd) {
                    showSetPay()
                    return@setOnClickListener
                }
                DialogHelper.showScanPayDialog(this){
                    showFuncScanDialog()
                }
            }
        }
        binding.rlOtherCard.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            showLoading()
            viewModel.getCouponList(null)
        }

        viewModel.error.observe(this) {
            if (isPause) {
                return@observe
            }
            hideLoading()
            showToast(it)
        }
        viewModel.paymentData.observe(this) {
            viewModel.queryAssets()
            binding.llOpen.visibility = View.VISIBLE
            val height: Int = AppUtils.dip2px(100F)
            val width: Int = AppUtils.dip2px(280F)

            val bitmap = ZXingUtils.createCode128(it.qr_code, width, height)
            binding.ivBarCode.setImageBitmap(bitmap)

            val bitmap2 = ZXingUtils.createQRCode(it.qr_code, AppUtils.dip2px(200F))
            binding.ivQrCode.setImageBitmap(bitmap2)

            binding.ivBarCode.visibility = View.VISIBLE
            binding.ivQrCode.visibility = View.VISIBLE
            binding.rlOtherCard.visibility = View.VISIBLE
            binding.llNoOpen.visibility = View.GONE

            dynCode = it.qr_code
            if (isPause) {
                return@observe
            }
            binding.ivQrCode.postDelayed({
                if (isPause) {
                    return@postDelayed
                }
                // 延迟2s查询结果
                if (!isFinish) {
                    viewModel.queryPayStatus(dynCode)
                }
            }, 2000)
        }

        viewModel.payStatus.observe(this) {
            if (isPause) {
                return@observe
            }
            if (it.status == "1") {
                // 过期 需要重新请求
                viewModel.getQrCode()
            } else {
                if (it.order_info != null) {
                    when (it.order_info.pay_result_code) {
                        "0", "1" -> {
                            // 0或1-待用户授权
                            startActivity(Intent(this, PaymentMerchantActivity::class.java).apply {
                                putExtra("qrCode", dynCode)
                                putExtra("order_info", it.order_info)
                            })
                            setResult(RESULT_OK)
                            finish()
                        }
                        "2" -> {
                            // 2-支付成功
                            startActivity(Intent(this, PaymentCompletedActivity::class.java).apply {
                                putExtra("balance", AppUtils.convertFenToYuan(it.order_info.amt))
                                putExtra("name", it.order_info.shop_name)
                                putExtra("payResult", "支付成功")
                            })
                            setResult(RESULT_OK)
                            finish()
                        }
                        "3" -> {
                            // 3-支付失败
                            startActivity(Intent(this, PaymentCompletedActivity::class.java).apply {
                                putExtra("balance", AppUtils.convertFenToYuan(it.order_info.amt))
                                putExtra("name", it.order_info.shop_name)
                                putExtra("payResult", "支付失败")
                            })
                            setResult(RESULT_OK)
                            finish()
                        }
                    }
                } else {
                    binding.ivQrCode.postDelayed({
                        if (isPause) {
                            return@postDelayed
                        }
                        // 延迟2s查询结果
                        if (!isFinish) {
                            viewModel.queryPayStatus(dynCode)
                        }
                    }, 2000)
                }
            }
        }

        viewModel.realName.observe(this) {
            hideLoading()
            dialogRealName?.dismiss()
            showToast("实名认证成功")
            // 判断是否设置支付密码
            val isSetPwd = SPHelper.getBoolean(SPKConstants.IS_SET_PWD)
            if (!isSetPwd) {
                showSetPay()
            }
        }
        viewModel.setPwd.observe(this) {
            hideLoading()
            showToast("支付密码设置成功")
            DialogHelper.showScanPayDialog(this){
                showFuncScanDialog()
            }
        }
        viewModel.setPayType.observe(this) {
            viewModel.queryAssets()
        }
        viewModel.myInfo.observe(this) {
            if (!TextUtils.isEmpty(it.name)) {
//                binding.tvPhone.text = it.cell
//                binding.tvName.text = it.name
//                binding.tvNamePhone.text = it.name + "(" + it.cell + ")"
            } else {
                binding.rlOtherCard.visibility = View.GONE
            }
            viewModel.getQrCode()
        }
        viewModel.couponPage.observe(this) {
            hideLoading()
            it?.let {
                mBeanList.clear()
                mBeanList.addAll(it.list)
            }
            showCouponSelectDialog()
        }

        viewModel.openScanPay.observe(this) {
            hideLoading()
            SPHelper.putBoolean(SPKConstants.IS_FUNC_SCAN, true)
            showToast("扫码支付开通成功")
            showLoading()
            viewModel.getQrCode()
        }
        viewModel.travelPassAssetsData.observe(this) {
            it?.let {
                assetsData = it
                selectPosition = it.selected
                passAssetsData = it.properties[it.selected]
                binding.tvNamePhone.text = passAssetsData!!.name + "(" + passAssetsData!!.tel + ")"
                binding.tvName.text = passAssetsData!!.name
                binding.tvPhone.text = passAssetsData!!.tel
                if (TextUtils.equals("1", passAssetsData!!.member_type)) {
                    binding.tvDesc.text = "优先使用旅通卡账户付款"
                } else {
                    binding.tvDesc.text = "使用亲属卡账户付款"
                }
            }
            hideLoading()
        }

        viewModel.scanQrCodeData.observe(this) {
            hideLoading()
            // 识别静态二维码成功
            isPause = true
            it?.let {
                startActivityForResult(Intent(this, PaymentMerchantActivity::class.java).apply {
                    putExtra("scanData", it)
                    putExtra("qrCode", resultSuccess)
                }, 112)
            }
        }

        viewModel.scanDynamicsQrCodeData.observe(this) {
            hideLoading()
            // 识别动态二维码成功
            isPause = true
            it?.let {
                startActivityForResult(Intent(this, PaymentMerchantActivity::class.java).apply {
                    putExtra("scanDynamicsData", it)
                    putExtra("qrCode", resultSuccess)
                }, 112)
            }
        }
    }

    override fun initData() {
        binding.statusBarView.layoutParams.height = CommonUtils.getStatusBarHeight()
        binding.llNoOpen.visibility = View.VISIBLE
        binding.llOpen.visibility = View.VISIBLE
        showLoading()
        viewModel.getMyInfo()
    }

    override fun initBinding(): FragmentPaymentCodeBinding {
        return FragmentPaymentCodeBinding.inflate(layoutInflater)
    }

    private fun showCouponSelectDialog() {
        couponSelectDialog = CouponSelectDialog(this, R.style.ActionSheetDialogStyle)
        couponSelectDialog?.setOnItemClickListener(object :
            CouponSelectDialog.OnConfirmClickListener {
            override fun onClickConfirm(itemBean: CouponItem?) {
                couponSelectDialog?.hideDialog()
                if (itemBean != null) {
                    isPause = true
                    // 跳转到二维码界面
                    startActivityForResult(
                        Intent(
                            this@PaymentCodeActivity,
                            QrCodeActivity::class.java
                        ).apply {
                            putExtra("coupon", itemBean)
                        }, 113
                    )
                }
            }

            override fun onClickQs(assetsData: TravelPassAssets) {
                couponSelectDialog?.hideDialog()
                passAssetsData = assetsData
                showLoading("设置中...")
                viewModel.setPayType(assetsData.kinship_id)
            }
        })
        couponSelectDialog?.setCouponList(mBeanList)
        couponSelectDialog?.setQsList(assetsData!!)
        couponSelectDialog?.show()
    }

    private fun scan() {
        val listP = listOf(Permission.CAMERA)
        if (EasyPermissions.isGranted(this, listP)) {
            startScan()
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    startScan()
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    DialogHelper.showPermissionHintDialog(this@PaymentCodeActivity, "相机服务未开启", "请在设置中为本应用开启相机服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(this@PaymentCodeActivity)
                    }
                }
                .request(
                    Permission.CAMERA,
                    getString(R.string.okpermission_camera),
                    getString(R.string.okpermission_camera_rationale)
                )
        }
    }

    private fun startScan() {
        val config = MNScanConfig.Builder().isShowPhotoAlbum(false)
        MNScanManager.startScan(this, config.builder()) { resultCode, data ->
            when (resultCode) {
                MNScanManager.RESULT_SUCCESS -> {
                    resultSuccess =
                        data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS)
                    resultSuccess?.let {
                        if (it.length > 32) {
                            showLoading("识别中...")
                            viewModel.scanQrCode(it)
                        } else {
                            // 商户动态码
                            showLoading("识别中...")
                            viewModel.scanDynamicsQrCode(it)
                        }
                    }
                }

                MNScanManager.RESULT_FAIL -> {
                    val resultError = data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR)
                    showToast(resultError)
                }

                MNScanManager.RESULT_CANCLE -> {
                    showToast("取消扫码")
                }
            }
        }
    }

    private fun showRealNameDialog() {
        dialogRealName = DialogRealName(this)
//        dialogRealName?.setCancelable(false)
//        dialogRealName?.setCanceledOnTouchOutside(false)
        dialogRealName?.setSureListener {
            // 实名认证
            val realName = dialogRealName?.getRealName()
            val realId = dialogRealName?.getRealId()
            if (TextUtils.isEmpty(realName)) {
                showToast("请输入真实姓名")
                return@setSureListener
            }
            if (TextUtils.isEmpty(realId)) {
                showToast("请输入身份证号")
                return@setSureListener
            }
            showLoading("实名认证中...")
            viewModel.realNameAuthentication(realName!!, realId!!)
        }
        dialogRealName?.show()
    }

    private fun showSetPay() {
        // 未设置支付密码
        DialogHelper.showPayHintDialog(this) {
            // 设置支付密码弹窗
            DialogHelper.showSetPayFirstDialog(this, object : SetPayCallback {
                override fun onSetPayResult(result: String) {
                    // 第二次弹出
                    payPassDialog =
                        DialogHelper.showSetPaySecondDialog(this@PaymentCodeActivity, object : SetPayCallback {
                            override fun onSetPayResult(resultSecond: String) {
                                if (!TextUtils.equals(result, resultSecond)) {
                                    showToast("两次输入的密码不一致")
                                    payPassDialog!!.payViewPass.cleanAllTv()
                                    return
                                }
                                payPassDialog?.dismiss()
                                showLoading("支付密码设置中...")
                                viewModel.setPayPassword(result)
                            }
                        })
                }
            })
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 112) {
            if (resultCode == RESULT_OK) {
                finish()
                return
            }
            if (isPause) {
                isPause = false
                if (!isFinish) {
                    viewModel.getQrCode()
                }
            }
        }
        if (requestCode == 113) {
            if (resultCode == RESULT_OK) {
                finish()
                return
            }
            if (isPause) {
                isPause = false
                if (!isFinish) {
                    viewModel.getQrCode()
                }
            }
        }
    }

    override fun onBackPressed() {
        isFinish = true
        super.onBackPressed()
    }

    override fun onDestroy() {
        isFinish = true
        super.onDestroy()
    }

    private fun showFuncScanDialog() {
        val funcScanDialog = FuncScanDialog(this, R.style.ActionSheetDialogStyle)
        funcScanDialog?.setOnItemClickListener(object :
            FuncScanDialog.OnConfirmClickListener {

            override fun onClickConfirm() {
                funcScanDialog?.hideDialog()
                // 开通扫码支付
                DialogHelper.showPayPwdDialog(this@PaymentCodeActivity, object : SetPayCallback {
                    override fun onSetPayResult(result: String) {
                        showLoading("开通中...")
                        viewModel.openScanPay(result)
                    }
                })
            }
        })
        funcScanDialog.show()
    }
}